from strategy_mode import Trading, TradingRules
import datetime

# from strategy_mode import TradingStrategy_05_03 as Strgs
import pandas as pd


def TradingMainLoop(
    df,
    day_lists,
    Strgs,  # 传入所使用的模型
    count_in=3,  # 间距
    line_Pares=3,
    simulation_type="test",
    Value_Pread_Mode="M",  # 计算周期
    AvableCash=100000,
    tradePersentDic={"X1": 1},
    fees_Persent=0.002,
    statsdic={
        "date": 0,
        "inPrice": 0,
        "outPrice": 0,
        "PreShare": 0,
        "HoldedHands": 0,
        "Share": 0,
        "AvableCash": 0,
        "TotalShareValues": 0,
        "ShareCost": 0,
        "new_SharePrise": 0,
        "SELL": 0,
        "BUY": 0,
        "treade": 0,
        "TYPES": "",
    },  # 交易用整体参数
):
    # tag_day="21_day",

    """
    交易参考代码
    """
    # 初始化交易用参数
    statsdic = {
        "date": 0,
        "inPrice": 0,
        "outPrice": 0,
        "PreShare": 0,
        "HoldedHands": 0,
        "Share": 0,
        "AvableCash": 0,
        "TotalShareValues": 0,
        "ShareCost": 0,
        "new_SharePrise": 0,
        "SELL": 0,
        "BUY": 0,
        "treade": 0,
        "TYPES": "",
        "TotalValues": 0,
    }
    statsdic["treade"] = 0
    df.drop_duplicates("date", inplace=True)
    statsdic["AvableCash"] = AvableCash
    statsdic["winValue"] = AvableCash
    statsdic["date"] = df.iloc[0]["date"]
    historyDate = []

    rang = int(df.shape[0] - 1)
    mode = "pass"

    if simulation_type == "test":
        trade_cuts = 0.05
    else:
        trade_cuts = 1

    tempdic = {}
    print("simulation start", end=" ")
    # print("= simulation CountStartPoint =".center(60, " "))
    starttime = datetime.datetime.now()
    prescale = 0
    for day in range(rang):
        scale = int((day / rang) * 100)
        if scale % 5 == 0 and prescale != scale:
            print("*", end="")
        prescale = scale

        d = day + 1

        df_d = df.iloc[d]
        df_day = df.iloc[day]
        df_day_1 = df.iloc[day - 1]

        if Value_Pread_Mode == "M":
            lindex = 1
        elif Value_Pread_Mode == "Y":
            lindex = 0

        datetimeO = str(statsdic["date"]).split("-")[lindex]
        datetimeN = str(df.iloc[d]["date"]).split("-")[lindex]

        statsdic["date"] = df.iloc[d]["date"]
        statsdic["outPrice"] = 0
        statsdic["BUY"] = 0
        statsdic["SELL"] = 0
        tradePersent = 0
        if int(datetimeO) != int(datetimeN):
            statsdic["winValue"] = statsdic["TotalValues"]

        mode, tradePersent, statsdic = Strgs.Main(
            df_day,
            df_day_1,
            mode=mode,
            line_Pares=line_Pares,
            tradePersent=tradePersent,
            day_lists=day_lists,
            day=day,
            statsdic=statsdic,
            count_in=count_in,
        )
        tradePersent = tradePersent * trade_cuts
        if mode != "pass" and tradePersent != 0:
            closePrice = df_day["close"]
            if mode.upper() == "BUY":
                statsdic["MARKER=B"] = closePrice
            else:
                statsdic["MARKER=S"] = closePrice
        else:
            mode = "pass"
            statsdic["treade"] = tradePersent
            statsdic["MARKER=B"] = None
            statsdic["MARKER=S"] = None

        dic, trade = Trading.tradingModel(
            df_d,
            df_day,
            statsdic,
            mode=mode,
            tradePersent=tradePersent,
            fees_Persent=fees_Persent,
        )  # 买卖规则

        statsdic["mode"] = mode
        # statsdic = tempinfo(statsdic, df_day, day_lists)
        historyDate.append(dic)
        del statsdic
        statsdic = dic.copy()
        statsdic["newPresent"] = statsdic["TotalValues"] / statsdic["winValue"]

        # print(statsdic)
    del statsdic
    df = pd.DataFrame(historyDate)
    df = DF_int2str(df, "treade")
    df = DF_int2str(df, "HoldingPresentage")
    df["MARKER=B"] = df["MARKER=B"].shift(-1)
    df["MARKER=S"] = df["MARKER=S"].shift(-1)

    df.loc[:, "TAG"] = (
        df.date + "_" + df.treade + "_" + df.HoldingPresentage + "_" + df.TYPES
    )
    statsdic = {
        "date": 0,
        "inPrice": 0,
        "outPrice": 0,
        "PreShare": 0,
        "HoldedHands": 0,
        "Share": 0,
        "AvableCash": 0,
        "TotalShareValues": 0,
        "ShareCost": 0,
        "new_SharePrise": 0,
        "SELL": 0,
        "BUY": 0,
        "treade": 0,
        "TYPES": "",
    }
    print("simulation  => {}s".format((datetime.datetime.now() - starttime).seconds))
    return df


# 构建算法标签
def DF_int2str(df, key):
    df.loc[:, key] = df.loc[:, key].apply(lambda x: str(x))
    return df


# def tempinfo(statsdic, df_day, day_lists):
#     statsdic["dLineC"] = TradingRules.MA_Sorter(
#         df_day, day_lists, key="close", method="count"
#     )
#     statsdic["dKeyBollC"] = TradingRules.key_key_BollSort(
#         df_day, day_lists, key="close", method="count"
#     )
#     statsdic["dPersentBollC"] = TradingRules.key_by_BollSort(
#         df_day, day_lists, key="close", method="count"
#     )

#     statsdic["dLineSup"] = TradingRules.MA_Sorter(df_day, day_lists, mode="UP")
#     statsdic["dKeyBollup"] = TradingRules.key_key_BollSort(df_day, day_lists, mode="UP")
#     statsdic["dPersentBollup"] = TradingRules.key_by_BollSort(
#         df_day, day_lists, mode="UP"
#     )

#     statsdic["dLineSdown"] = TradingRules.MA_Sorter(df_day, day_lists, mode="DOWN")
#     statsdic["dKeyBollSdown"] = TradingRules.key_key_BollSort(
#         df_day, day_lists, mode="DOWN"
#     )
#     statsdic["dPersentBollSdown"] = TradingRules.key_by_BollSort(
#         df_day, day_lists, mode="DWON"
#     )
#     return statsdic